package com.presto.directo.utils

import com.orhanobut.logger.Logger
import com.presto.directo.base.XApplication
import com.presto.directo.entity.BaseEntity
import es.dmoral.toasty.Toasty
import kotlinx.coroutines.*

val UNKNOWN_MISTAKE = "Error desconocido"
val SUCCESS = 200

fun CoroutineScope.start(
    onNext: suspend () -> Unit,
    onError: ((throwable: Throwable) -> Unit)? = null,
    onComplete: (() -> Unit)? = null,
    toast: Boolean = true
): Job {
    return launch(CoroutineExceptionHandler { coroutineContext, throwable ->
        Logger.e(throwable.message ?: "")
        onError?.invoke(throwable)
        onComplete?.invoke()
        if (toast) {
            Toasty.error(XApplication.application, (throwable.message ?: "").ifEmpty { UNKNOWN_MISTAKE }).show()
        }
    }) {
        onNext()
        onComplete?.invoke()
    }
}

fun <T> BaseEntity<T>.getResult(): T {
    if (code != SUCCESS || result == null) {
        throw MyException(if (message.isNotEmpty()) message else code.toString(), code)
    }
    return result
}

fun <T> BaseEntity<T>.getResultOrNull(): T? {
    if (code != SUCCESS) {
        throw MyException(if (message.isNotEmpty()) message else code.toString(), code)
    }
    return result
}

class MyException(message: String?, val code: Int) : Exception(message) {

}